package com.ogj.shiro.config;

import com.ogj.shiro.entity.User;
import com.ogj.shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义Realm
 *
 */

public class UserRealm extends AuthorizingRealm {

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //给资源进行授权
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        //到数据库查询当前登录用户的授权字符串
        //获取当前登录用户
        Subject subject= SecurityUtils.getSubject();
        User user=(User) subject.getPrincipal(); //拿到当前用户的权限,在日常开发中，权限和用户信息在两个表中,所以这里需要查询两次
        User dbUser = userService.getUserById(user.getId()); //拿到这个用户的所有信息
        info.addStringPermission(dbUser.getPerms());

        return info;
    }


    @Autowired
    UserService userService;
    /**
     * 执行认证逻辑
     * @param arg0
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        //编写shiro判断逻辑
        //1、判断用户名
        UsernamePasswordToken token=(UsernamePasswordToken) arg0;
        //首先判断有没有这个人
        if(userService.getUserCountByUsername(token.getUsername())==0){
            //用户名 不存在
            return null; //shiro底层会抛出UnknowAccountException
        }
        //2、判断密码
//        第一个参数：subject.getPrincipal(); 传入查询到的对象
        return new SimpleAuthenticationInfo(userService.getUserPasswordByUsername(token.getUsername()),userService.getUserPasswordByUsername(token.getUsername()).getPassword(),"");
    }
}
